<template>
  <div class="userInfo">
    <van-nav-bar
      title="修改用户资料"
      fixed
      left-arrow
      @click-left="$router.back()"
    />
    <van-cell title="头像" is-link @click="$refs.avarat.chooseFile()">
      <template #default>
        <van-image
          round
          fit="cover"
          :src="'http://124.223.14.236:8060/' + userInfo.icon"
        />
      </template>
    </van-cell>
    <van-cell
      title="昵称"
      is-link
      :value="userInfo.username"
      @click="showNameFn"
    />
    <van-cell
      title="手机号"
      is-link
      :value="userInfo.mobile"
      @click="showMobileFn"
    />
    <van-cell
      title="性别"
      is-link
      :value="userInfo.sex === 0 ? '男' : '女'"
      @click="showGender = true"
    />
    <van-cell
      title="出生年月"
      is-link
      :value="userInfo.birthday"
      @click="showBirthdayFn"
    />
    <van-cell
      title="家庭住址"
      is-link
      :label="userInfo.address"
      @click="showAddress = true"
    />
    <van-cell
      title="个性留言"
      is-link
      :label="userInfo.notes"
      @click="showNotesFn"
    />

    <!-- 昵称弹出框 -->
    <van-dialog
      @confirm="updateName"
      v-model="showName"
      title="编辑昵称"
      show-cancel-button
    >
      <van-field
        show-word-limit
        maxlength="7"
        ref="nickname"
        v-model.trim="newName"
        placeholder="请输入昵称"
      />
    </van-dialog>
    <!-- 手机号弹出框 -->
    <van-dialog
      v-model="showMobile"
      title="修改手机号"
      show-cancel-button
      :showConfirmButton="false"
    >
      <van-form>
        <van-field
          v-model.trim="newMobile"
          label="手机号"
          placeholder="请输入手机号"
          :rules="rules.mobile"
        />
        <div style="margin: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            @click="updateMobile"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </van-dialog>
    <!-- 性别弹出框 -->
    <van-popup v-model="showGender" position="bottom">
      <van-picker
        title="标题"
        show-toolbar
        :default-index="userInfo.sex"
        :columns="columns"
        @cancel="showGender = false"
        @confirm="updateSex"
      />
    </van-popup>
    <!-- 年龄弹出框 -->
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthday = false"
        @confirm="updateBirthday"
      />
    </van-popup>
    <!-- 地址弹出框 -->
    <van-popup v-model="showAddress" position="bottom">
      <van-area
        title="标题"
        :value="code"
        :area-list="areaList"
        @confirm="updateAddress"
        @cancel="showAddress = false"
      />
    </van-popup>
    <!-- 留言弹出框 -->
    <van-dialog
      @confirm="updateNotes"
      v-model="showNotes"
      title="编辑个性留言"
      show-cancel-button
    >
      <van-field
        ref="nicknotes"
        :clearable="true"
        style="padding-top: 5px"
        v-model.trim="newNotes"
        rows="2"
        autosize
        type="textarea"
        maxlength="50"
        placeholder="请输入留言"
        show-word-limit
      />
    </van-dialog>
    <!-- 头像 -->
    <div>
      <van-uploader :after-read="afterRead" v-show="false" ref="avarat" />
      <div class="mask" v-if="showMask">
        <VueCropper
          ref="cropper"
          :img="img"
          autoCrop
          autoCropWidth="375"
          autoCropHeight="375"
          fixed
          :canMoveBox="false"
          :centerBox="true"
        ></VueCropper>
        <van-button type="primary" class="confirm" @click="cropFn">
          确认
        </van-button>
        <van-button type="info" class="cancel" @click="showMask = false">
          取消
        </van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import moment from 'moment'
import { alterUserInfo, tou } from '@/api/user'
import { mapActions, mapState } from 'vuex'
import { areaList } from '@vant/area-data'
export default {
  components: {
    VueCropper
  },
  data() {
    return {
      newName: '',
      newMobile: '',
      newNotes: '',
      img: '',
      showName: false,
      showMobile: false,
      showGender: false,
      showBirthday: false,
      showAddress: false,
      showNotes: false,
      showMask: false,
      rules: {
        mobile: [
          { required: true, message: '请填写用户名' },
          {
            pattern:
              /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '请输入正确手机号'
          }
        ]
      }, // 手机号校验
      columns: ['男', '女'],
      minDate: new Date(1900, 0, 1),
      maxDate: new Date(),
      currentDate: '',
      areaList,
      code: localStorage.getItem('code')
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['actions_getUser']),
    // ? 回显昵称
    async showNameFn() {
      this.showName = true
      this.newName = this.userInfo.username
      await this.$nextTick()
      this.$refs.nickname.focus()
    },
    // ? 发送请求修改昵称
    async updateName() {
      if (this.newName.length === 0) {
        return this.$toast('内容不能为空')
      }
      if (this.newName !== this.userInfo.username) {
        await alterUserInfo({
          id: this.userInfo.id,
          username: this.newName
        })
        this.$toast('修改昵称成功')
        await this.$nextTick()
        this.actions_getUser()
      }
    },
    // ? 回显手机号
    showMobileFn() {
      this.showMobile = true
      this.newMobile = this.userInfo.mobile
    },
    // ? 发送请求修改手机号
    async updateMobile() {
      const a =
        /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
          this.newMobile
        )
      if (this.newMobile !== this.userInfo.mobile && a) {
        await alterUserInfo({
          id: this.userInfo.id,
          mobile: this.newMobile
        })
        this.$toast('修改手机号成功')
        await this.$nextTick()
        this.actions_getUser()
        this.showMobile = false
      }
      if (this.newMobile === this.userInfo.mobile) this.showMobile = false
    },
    // ? 发送请求修改性别
    async updateSex(val, index) {
      if (this.userInfo.sex !== index) {
        await alterUserInfo({
          id: this.userInfo.id,
          sex: index
        })
        this.$toast('修改性别成功')
        await this.$nextTick()
        this.actions_getUser()
      }
      this.showGender = false
    },
    // ? 回显年龄
    showBirthdayFn() {
      this.showBirthday = true
      this.currentDate = new Date(this.userInfo.birthday)
    },
    // ? 发送请求修改年龄
    async updateBirthday() {
      if (
        this.userInfo.birthday !== moment(this.currentDate).format('YYYY-MM-DD')
      ) {
        await alterUserInfo({
          id: this.userInfo.id,
          birthday: moment(this.currentDate).format('YYYY-MM-DD')
        })
        this.$toast('修改年龄成功')
        await this.$nextTick()
        this.actions_getUser()
      }
      this.showBirthday = false
    },
    // ? 发送请求修改地址
    async updateAddress(val) {
      let str = ''
      for (let i = 0; i < val.length; i++) {
        str += val[i].name + ' '
      }

      if (str !== this.userInfo.address) {
        await alterUserInfo({
          id: this.userInfo.id,
          address: str
        })
        localStorage.setItem('code', val[2].code)
        this.$toast('修改地址成功')
        await this.$nextTick()
        this.actions_getUser()
      }
      this.showAddress = false
    },
    // ? 回显留言
    async showNotesFn() {
      this.showNotes = true
      this.newNotes = this.userInfo.notes
      await this.$nextTick()
      this.$refs.nicknotes.focus()
    },
    // ? 发送请求修改留言
    async updateNotes() {
      if (this.newNotes.length === 0) {
        return this.$toast('内容不能为空')
      }
      if (this.newNotes !== this.userInfo.notes) {
        await alterUserInfo({
          id: this.userInfo.id,
          notes: this.newNotes
        })
        this.$toast('修改留言成功')
        await this.$nextTick()
        this.actions_getUser()
      }
    },
    // ? 头像
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      this.showMask = true
      this.img = file.content
    },
    // ? 发送请求修改图片
    cropFn() {
      this.$refs.cropper.getCropBlob(async (data) => {
        // do something
        const fd = new FormData()
        fd.append('file', data)
        const res = await tou(fd)
        this.img = res.data.savePath

        await alterUserInfo({
          icon: this.img,
          id: this.userInfo.id
        })

        this.$toast.success('修改头像成功')
        this.showMask = false
        this.actions_getUser()
      })
    }
  },
  created() {
    this.actions_getUser()
  }
}
</script>

<style lang="less" scoped>
.userInfo {
  padding-top: 46px;
  .van-popup {
    .van-nav-bar {
      background-color: #fff;
      ::v-deep {
        .van-nav-bar__title {
          color: #000;
        }
      }
    }
  }
  ::v-deep {
    .van-image__img {
      width: 30px;
      height: 30px;
    }
  }
  .mask {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    .confirm,
    .cancel {
      position: absolute;
      bottom: 0;
    }
    .confirm {
      left: 0;
    }
    .cancel {
      right: 0;
    }
  }
}
</style>
